package com.uniflow.controller;

import com.uniflow.common.PageResult;
import com.uniflow.common.Result;
import com.uniflow.entity.ProcessInstance;
import com.uniflow.entity.TaskCenter;
import com.uniflow.entity.Form;
import com.uniflow.service.WorkflowService;
import com.uniflow.service.TaskCenterService;
import com.uniflow.service.UniflowFormService;
import com.uniflow.service.AuthService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;
import com.uniflow.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 * 流程管理控制器
 * 提供流程定义、流程实例相关的API接口
 */
@RestController
@RequestMapping("/api/v1/processes")
@Api(tags = "流程管理")
public class ApiController {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private WorkflowService workflowService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private TaskCenterService taskCenterService;
    
    @Autowired
    private UniflowFormService formService;
    
    // ==================== 用户认证相关 ====================
    
    /**
     * 用户登录
     */
    @PostMapping("/auth/login")
    @ApiOperation("用户登录")
    public Result<Map<String, Object>> login(@RequestBody @Valid LoginRequest request) {
        try {
            Map<String, Object> result = authService.login(request.getUsername(), request.getPassword());
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/auth/logout")
    @ApiOperation("用户登出")
    public Result<Void> logout(HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                String userId = jwtUtil.getUserIdFromToken(token);
                authService.logout(userId);
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error("登出失败: " + e.getMessage());
        }
    }
    
    // ==================== 流程相关API ====================
    
    /**
     * 启动流程实例
     */
    @PostMapping("/process/start")
    @ApiOperation("启动流程实例")
    public Result<ProcessInstance> startProcess(@RequestBody @Valid StartProcessRequest request) {
        try {
            ProcessInstance instance = workflowService.startProcess(
                    request.getProcessKey(),
                    request.getBusinessKey(),
                    request.getVariables(),
                    request.getStartUserId());
            return Result.success(instance);
        } catch (Exception e) {
            return Result.error("启动流程失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询流程实例列表
     */
    @GetMapping("/process/instances")
    @ApiOperation("查询流程实例列表")
    public Result<PageResult<ProcessInstance>> getProcessInstances(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("流程定义键") @RequestParam(required = false) String processDefinitionKey,
            @ApiParam("业务键") @RequestParam(required = false) String businessKey,
            @ApiParam("启动用户ID") @RequestParam(required = false) String startUserId,
            @ApiParam("是否完成") @RequestParam(required = false) Boolean finished) {
        try {
            PageResult<ProcessInstance> result = workflowService.getProcessInstanceList(
                    pageNum, pageSize, processDefinitionKey, businessKey, startUserId, finished);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询流程实例失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询流程实例详情
     */
    @GetMapping("/process/instances/{id}")
    @ApiOperation("根据ID查询流程实例详情")
    public Result<ProcessInstance> getProcessInstanceById(
             @PathVariable @NotBlank String id) {
        try {
            ProcessInstance instance = workflowService.getProcessInstanceById(id);
            return Result.success(instance);
        } catch (Exception e) {
            return Result.error("查询流程实例详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 终止流程实例
     */
    @DeleteMapping("/process/instances/{id}")

    public Result<Void> terminateProcessInstance(
            @ApiParam("流程实例ID") @PathVariable @NotBlank String id,
            @ApiParam("终止原因") @RequestParam(required = false) String reason) {
        try {
            workflowService.deleteProcessInstance(id, reason);
            return Result.success();
        } catch (Exception e) {
            return Result.error("终止流程实例失败: " + e.getMessage());
        }
    }
    
    // ==================== 任务相关API ====================
    
    /**
     * 获取待办任务列表
     */
    @GetMapping("/tasks/pending")
    @ApiOperation("获取待办任务列表")
    public Result<Map<String, Object>> getPendingTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("任务类型") @RequestParam(required = false) String type,
            @ApiParam("优先级") @RequestParam(required = false) Integer priority) {
        try {
            PageResult<TaskCenter> result = taskCenterService.getMyTasks(
                    pageNum, pageSize, assigneeId, "pending", type, priority, null);
            
            Map<String, Object> response = new HashMap<>();
            response.put("tasks", result.getList());
            response.put("count", result.getTotal());
            response.put("page", pageNum);
            response.put("size", pageSize);
            response.put("totalPages", result.getPages());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取待办任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成任务
     */
    @PostMapping("/tasks/{taskId}/complete")
    @ApiOperation("完成任务")
    public Result<Void> completeTask(
            @ApiParam("任务ID") @PathVariable @NotBlank String taskId,
            @RequestBody @Valid CompleteTaskRequest request) {
        try {
            String action = request.getAction();
            switch (action) {
                case "approve":
                    workflowService.approveTask(taskId, request.getComment(), request.getVariables());
                    break;
                case "reject":
                    workflowService.rejectTask(taskId, request.getComment(), request.getVariables());
                    break;
                case "transfer":
                    if (request.getTransferTo() == null || request.getTransferTo().trim().isEmpty()) {
                        return Result.error("转办目标用户不能为空");
                    }
                    workflowService.transferTask(taskId, request.getTransferTo(), request.getComment());
                    break;
                default:
                    workflowService.completeTask(taskId, request.getVariables(), request.getComment());
                    break;
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error("操作任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 认领任务
     */
    @PostMapping("/tasks/{taskId}/claim")
    @ApiOperation("认领任务")
    public Result<Void> claimTask(
            @ApiParam("任务ID") @PathVariable @NotBlank String taskId,
            @RequestBody @Valid ClaimTaskRequest request) {
        try {
            taskCenterService.claimTask(taskId, request.getUserId(), request.getUserId());
            return Result.success();
        } catch (Exception e) {
            return Result.error("认领任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务详情
     */
    @GetMapping("/tasks/{taskId}")
    @ApiOperation("获取任务详情")
    public Result<TaskCenter> getTaskById(
            @ApiParam("任务ID") @PathVariable @NotBlank String taskId) {
        try {
            TaskCenter task = taskCenterService.getTaskById(taskId);
            return Result.success(task);
        } catch (Exception e) {
            return Result.error("获取任务详情失败: " + e.getMessage());
        }
    }
    
    // ==================== 表单定义API ====================
    
    /**
     * 获取表单Schema定义
     */
    @GetMapping("/forms/{formKey}/schema")
    @ApiOperation("获取表单Schema定义")
    public Result<Map<String, Object>> getFormSchema(
            @ApiParam("表单Key") @PathVariable @NotBlank String formKey) {
        try {
            Form form = formService.getFormByName(formKey);
            if (form == null) {
                return Result.error("表单不存在: " + formKey);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("schema", form.getConfig() != null ? form.getConfig() : new HashMap<>());
            response.put("uiSchema", form.getStyle() != null ? form.getStyle() : new HashMap<>());
            response.put("formKey", formKey);
            response.put("title", form.getTitle() != null ? form.getTitle() : form.getName());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取表单Schema失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证表单数据
     */
    @PostMapping("/forms/{formKey}/validate")
    @ApiOperation("验证表单数据")
    public Result<Map<String, Object>> validateFormData(
            @ApiParam("表单Key") @PathVariable @NotBlank String formKey,
            @RequestBody Map<String, Object> formData) {
        try {
            // 这里可以添加表单数据验证逻辑
            Map<String, Object> result = new HashMap<>();
            result.put("valid", true);
            result.put("errors", new ArrayList<>());
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("验证表单数据失败: " + e.getMessage());
        }
    }
    
    // ==================== 请求数据结构 ====================
    
    public static class LoginRequest {
        @NotBlank(message = "用户名不能为空")
        private String username;
        
        @NotBlank(message = "密码不能为空")
        private String password;
        
        private boolean rememberMe = false;
        
        // getters and setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public boolean isRememberMe() { return rememberMe; }
        public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; }
    }
    
    public static class StartProcessRequest {
        @NotBlank(message = "流程Key不能为空")
        private String processKey;
        
        private String businessKey;
        private Map<String, Object> variables;
        private Map<String, Object> formData;
        private String startUserId;
        
        // getters and setters
        public String getProcessKey() { return processKey; }
        public void setProcessKey(String processKey) { this.processKey = processKey; }
        public String getBusinessKey() { return businessKey; }
        public void setBusinessKey(String businessKey) { this.businessKey = businessKey; }
        public Map<String, Object> getVariables() { return variables; }
        public void setVariables(Map<String, Object> variables) { this.variables = variables; }
        public Map<String, Object> getFormData() { return formData; }
        public void setFormData(Map<String, Object> formData) { this.formData = formData; }
        public String getStartUserId() { return startUserId; }
        public void setStartUserId(String startUserId) { this.startUserId = startUserId; }
    }
    
    public static class CompleteTaskRequest {
        @NotBlank(message = "操作类型不能为空")
        private String action; // approve, reject, transfer
        
        private String comment;
        private Map<String, Object> variables;
        private String transferTo; // 转办给谁
        
        // getters and setters
        public String getAction() { return action; }
        public void setAction(String action) { this.action = action; }
        public String getComment() { return comment; }
        public void setComment(String comment) { this.comment = comment; }
        public Map<String, Object> getVariables() { return variables; }
        public void setVariables(Map<String, Object> variables) { this.variables = variables; }
        public String getTransferTo() { return transferTo; }
        public void setTransferTo(String transferTo) { this.transferTo = transferTo; }
    }
    
    public static class ClaimTaskRequest {
        @NotBlank(message = "用户ID不能为空")
        private String userId;
        
        // getters and setters
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
    }
}